import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '@/store';
Vue.use(VueRouter);
import { Toast } from 'vant';

// 路由懒加载
const MyLogin = () => import('@/views/MyLogin');
const Layout = () => import('@/views/Layout');
const MyHome = () => import('@/views/MyHome');
const MyAsk = () => import('@/views/MyAsk');
const MyVideo = () => import('@/views/MyVideo');
const MyMine = () => import('@/views/MyMine');
const MyMineEdit = () => import('@/views/MyMine/MyMineEdit');
const MyArticle = () => import('@/views/MyArticle');
const MySearch = () => import('@/views/MySearch');
const MyResult = () => import('@/views/MySearch/MyResult');
const Chat = () => import('@/views/MyMine/Chat');

const routes = [
	{ path: '/', redirect: '/layout/home' },
	{
		name: 'layout',
		path: '/layout',
		component: Layout,
		children: [
			{
				name: 'home',
				path: 'home',
				component: MyHome,
				meta: { needCache: true },
			},
			{ name: 'ask', path: 'ask', component: MyAsk },
			{ name: 'video', path: 'video', component: MyVideo },
			{
				name: 'mine',
				path: 'mine',
				component: MyMine,
				meta: { needLogin: true },
			},
		],
	},
	{ name: 'login', path: '/login', component: MyLogin },
	{ name: 'mymineedit', path: '/edit', component: MyMineEdit },
	{ name: 'myarticle', path: '/article', component: MyArticle },
	{ name: 'mysearch', path: '/search', component: MySearch },
	{ name: 'result', path: '/search/result', component: MyResult },
	{ name: 'chat', path: '/mine/chat', component: Chat },
];

const router = new VueRouter({
	routes,
});

// 解决3.1版本后在控制台出现的警告
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
	if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject);
	return originalPush.call(this, location).catch((err) => err);
};

// 导航守卫
router.beforeEach((to, from, next) => {
	if (to.meta.needLogin) {
		if (store.state.tokenObj.token) {
			next();
		} else {
			Toast('请先登录');
			next({
				name: 'login',
				query: {
					back: to.path,
				},
			});
		}
	} else {
		next();
	}
});

export default router;
